package com.daisuxia.risk.service;

import java.util.HashMap;
import java.util.LinkedHashMap;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.risk.utils.jyzx.JsonSerializer;
import com.daisuxia.risk.utils.jyzx.Pkg1003;
import com.daisuxia.risk.utils.jyzx.PkgHeader;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.util.OrderNoUtil;
/**
 * 91征信
 * @author zhangsh Tel:13817876783
 * @date 2017年10月18日 上午9:18:46
 * @Title: JyzxService
 * @ClassName: JyzxService
 * @Description:
 */
@Service
public class JyzxService implements IJyzxService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskOrdersService riskOrdersService;

	@Override
	public ServiceResult getBorrow(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			if (userName != null && cardNum != null && userId != null) {
				LinkedHashMap<String, String> map2 = SysCacheUtils
						.getConfigParams(BackConfigParams.JYZX);
				String url = map2.get("JYZX_URL");

				Pkg1003 pkg1001 = new Pkg1003();
				pkg1001.setIdCard(cardNum + "");
				pkg1001.setRealName(userName + "");
				PkgHeader reqPkg = new PkgHeader();
				PkgHeader rspPkg = new PkgHeader();
				reqPkg.setVersion("01"); // 默认01
				reqPkg.setCustNo(map2.get("JYZX_JGDM")); // 公司代码
				reqPkg.setEncode("01"); // 01.UTF8 02.GBK
				reqPkg.setTrxCode("1003"); // 报文编号 默认四位 例:0001
				reqPkg.setEncryptType("01"); // 加密类型 01.不加密 02.RSA
				reqPkg.setMsgType("01"); // 01.JSON 02.XML 03.Protobuf
				reqPkg.setMsgBody(JsonSerializer.serializer(pkg1001)); // 报文主体
				reqPkg.setSign(map2.get("JYZX_SIGN")); // 签名
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.JYZX);
				orders.setAct(ConstantRisk.JYZX_BORROW);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams("url=" + url + ",reqPkg="
						+ reqPkg.toString());
				logger.info("91 card"+cardNum);
//				logger.info("getBorrow send  " + orders.toString());
				riskOrdersService.insert(orders);

				CloseableHttpClient httpclient = HttpClients.createDefault();
				HttpPost post = new HttpPost(url);
				ByteArrayEntity reqEntity = new ByteArrayEntity(reqPkg
						.toPkgBytes("UTF-8"));
				post.setEntity(reqEntity);

				CloseableHttpResponse response = null;
				String result = "";
				try {
					RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();// 设置请求和传输超时时间
					post.setConfig(requestConfig);
					response = httpclient.execute(post);
					HttpEntity rspEntity = response.getEntity();
					if (rspEntity != null) {
						result = EntityUtils.toString(rspEntity);
					}
//					logger.info("getBorrow return " + result);
					if (StringUtils.isNotBlank(result)) {
						rspPkg.parseFromString(result); // 解析报文头
						if ("0000".equals(rspPkg.getRetCode())) {
							serviceResult = new ServiceResult(
									ServiceResult.SUCCESS, rspPkg.getMsgBody());
							orders.setStatus(RiskOrders.STATUS_SUC);
						} else {
							serviceResult = new ServiceResult("300", rspPkg
									.getRetMsg());
						}
						orders.setReturnParams(result);
						riskOrdersService.update(orders);
					} else {
						orders.setReturnParams("return null");
						serviceResult = new ServiceResult("100", "返回空或请求报错");
					}
					riskOrdersService.update(orders);
				} catch (Exception e) {
					logger.error(
							"send to 91 error reqPkg=" + reqPkg.toString(), e);
				}
				response.close();
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getBorrow error ,params=" + params, e);
		}
		return serviceResult;
	}

}
